package com.demo.sentinel.command;

import lombok.SneakyThrows;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;


/**
 * @ClassName Desasdf
 * @Description TODO
 * @Author hf
 * @Date 2023/2/6 9:56
 * @Version 1.0
 */
public class TestSp {


    static class Red implements Runnable {
        @SneakyThrows
        @Override
        public void run() {
            semaphore.acquire();
            System.out.println("红灯亮");
            for (int i = 5; i >= 0; i--) {
                System.out.println("倒计时" + i);
                TimeUnit.SECONDS.sleep(1);
            }
            semaphore.release();
        }
    }

    static class Yellow implements Runnable {
        @SneakyThrows
        @Override
        public void run() {
            semaphore.acquire();
            System.out.println("黄灯亮");
            for (int i = 2; i >= 0; i--) {
                System.out.println("倒计时" + i);
                TimeUnit.SECONDS.sleep(1);
            }
            semaphore.release();
        }
    }


    static class Green implements Runnable {
        @SneakyThrows
        @Override
        public void run() {
            semaphore.acquire();
            System.out.println("绿灯亮");
            for (int i = 3; i >= 0; i--) {
                System.out.println("倒计时" + i);
                TimeUnit.SECONDS.sleep(1);
            }
            semaphore.release();

        }
    }

    private static Semaphore semaphore = new Semaphore(2);

    public static void main(String[] args) throws InterruptedException, BrokenBarrierException {
        Green green = new Green();
        Yellow yellow = new Yellow();
        Red red = new Red();
        new Thread(() -> {
            while (true)
            {
                green.run();
                yellow.run();
                red.run();
            }

        }).start();

    }
}
